package com.starblink.wishlist.search.ui

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.flexbox.*
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.*
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.widget.ConfirmDialog
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.library.widget.holder.HistoryAdapter
import com.starblink.wishlist.databinding.ActivityWishlistSearchBinding
import com.starblink.wishlist.wishallitems.ui.WishAllItemsFragment

@Route(path = RoutePage.Wishlist.WISHLIST_SEARCH)
class WishlistSearchActivity : BaseTVMActivity<ActivityWishlistSearchBinding, WishlistSearchVM>() {

    lateinit var wishAllItemsFragment: WishAllItemsFragment
    private var choiceMode = false
    override fun initViewBinding(): ActivityWishlistSearchBinding =
        ActivityWishlistSearchBinding.inflate(layoutInflater)

    private val historyAdapter by lazyOnNone {
        HistoryAdapter(viewBinding.recyclerHistory, viewModel.history) {
            viewBinding.editSearchEditTxt.editText.setText(it)
            viewBinding.editSearchEditTxt.editText.setSelection(it.length)
            doSearchAction(it)
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.queryHistory()
        initHistoryRecycleView()
        setView()
        initFragment()
        startObserve()
    }

    //点击右上设置按钮
    private fun clickRightTopSetting() {
        //设置隐藏
        viewBinding.ivSetting.gone()
        //gone 出现
        wishAllItemsFragment.showFillView(true)
        viewBinding.mutiChoiceMode.visible()
    }


    //重置全选模式
    private fun resetAllMuti(click: Boolean) {
        viewBinding.ivSetting.visible()
        wishAllItemsFragment.showFillView(false)
        viewBinding.mutiChoiceMode.gone()

        if (click) {
            choiceMode = !choiceMode
            wishAllItemsFragment.intoMutiSelect(choiceMode)
        }

    }


    private fun setView() {
        viewBinding.editSearchEditTxt.editText.requestFocus()
        viewBinding.editSearchEditTxt.editText.imeOptions = EditorInfo.IME_ACTION_SEARCH
        viewBinding.editSearchEditTxt.editText.setOnEditorActionListener { _, actionId, _ ->
            if (EditorInfo.IME_ACTION_SEARCH == actionId) {
                doSearchAction(viewBinding.editSearchEditTxt.editText.text)
                true
            } else {
                false
            }
        }
        viewBinding.editSearchEditTxt.editText.addTextChangedListenerClosure {
            if (it.isBlank()) {
                doSearchAction("")
            }
        }
        viewBinding.cancel.click {
            finish()
        }
        viewBinding.editTag.click {
            viewBinding.editSearchEditTxt.visible()
            viewBinding.editTagTxt.text = ""
            viewBinding.editSearchEditTxt.text = ""
            viewBinding.editTag.gone()
        }

        viewBinding.btnDelete.setOnClickListener {
            ConfirmDialog.Builder(this)
                .setCancelButton(com.starblink.basic.style.R.string.delete) { dialog, _ ->
                    viewModel.clearHistory()
                    dialog.dismiss()
                }
                .setSureButton(com.starblink.basic.style.R.string.cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .setTitle(com.starblink.basic.style.R.string.clear_recent_view)
                .create().show()
        }

        //多选处理
        viewBinding.ivSetting.setOnClickListener {
            choiceMode = !choiceMode
            wishAllItemsFragment.intoMutiSelect(choiceMode)
            if (choiceMode) {
                clickRightTopSetting()
            }
        }
        viewBinding.mutiChoiceMode.click {
            resetAllMuti(click = true)
        }
    }

    private fun initHistoryRecycleView() {
        viewBinding.recyclerHistory.layoutManager = FlexboxLayoutManager(this).apply {
            flexDirection = FlexDirection.ROW
            justifyContent = JustifyContent.FLEX_START
            maxLine = 10
            flexWrap = FlexWrap.WRAP
            // alignContent = AlignContent.FLEX_END // not support
        }
        viewBinding.recyclerHistory.addItemDecoration(FlexboxItemDecoration(this).apply {
            setDrawable(object : ColorDrawable(Color.TRANSPARENT) {
                override fun getIntrinsicWidth(): Int = 8.dp2px()
                override fun getIntrinsicHeight(): Int = 8.dp2px()
            })
        })
        viewBinding.recyclerHistory.adapter = historyAdapter

    }


    private fun startObserve() {
        viewModel.historyLD.observe(this) {
            viewBinding.clHistory.visibleOrGone(it) {
                historyAdapter.notifyItemRangeChanged(0, historyAdapter.itemCount)
            }
        }

    }

    private fun doSearchAction(searchContent: CharSequence?) {
        if (!searchContent.isNullOrEmpty()) {
            val keyword = searchContent.toString()
            viewModel.curKeyword = keyword
            saveQuery(keyword)
            //设置搜索关键字 左匹配
            wishAllItemsFragment.setSearchTitleKey(keyword)
            wishAllItemsFragment.refreshMainData(showSimpleDialog = true)
            searchProduct()

            viewBinding.editSearchEditTxt.gone()
            viewBinding.editTagTxt.text = keyword
            viewBinding.editTag.visible()
        } else {
            hideFragment()
            historyAdapter.notifyDataSetChanged()
            viewBinding.clHistory.visible()

            viewBinding.cancel.visible()
            viewBinding.back.gone()
            viewBinding.ivSetting.gone()
            viewBinding.editSearchEditTxt.visible()
            viewBinding.editTagTxt.text = ""
            viewBinding.editTag.gone()
        }

    }

    private fun searchProduct() {
        viewBinding.clHistory.visibleOrGone(false) {}
        showFragment()
    }

    private fun saveQuery(word: String) {
        viewModel.saveHistory(word)
    }

    private var index0Size = 0
    private fun initFragment() {
        viewBinding.fragmentContainerView.invisible()
        wishAllItemsFragment = WishAllItemsFragment.obtainFragment(displayType = 1)
        this.fragmentManager {
            addFragment(com.starblink.wishlist.R.id.fragment_container_view, wishAllItemsFragment)
        }
        wishAllItemsFragment.setDataChangeListener { size, selectAll, noData ->
            index0Size = size
            if (index0Size > 0) {
                viewBinding.cancel.gone()
                viewBinding.back.visible()
                viewBinding.ivSetting.visible()
            } else {
                viewBinding.cancel.visible()
                viewBinding.back.gone()
                viewBinding.ivSetting.gone()
            }
        }
    }

    private fun hideFragment() {
        this.hideFragment(wishAllItemsFragment)
        viewBinding.fragmentContainerView.invisible()
    }

    private fun showFragment() {
        this.showFragment(wishAllItemsFragment)
        viewBinding.fragmentContainerView.visible()
    }

}